﻿
//Author: 张亚涛
//createtime:2015-12-24 23:28:08
//Description: 

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model;
using DAL;
using NS.BLL.Systems;
using WechatUtility;
using System.Collections;
using NS.Model.Systems;
using WxPay;

namespace BLL
{

    /// <summary>
    /// 该类提供了一系列操作 "Order" 表的方法;
    /// </summary>
    public class OrderService
    {
        #region .对本表的维护.
        #region select data
        /// <summary>
        /// 返回Order表的所有数据  
        /// </summary>
        /// <param name="OpenID">微信ID</param>
        /// <param name="State">状态(wf:未付 yf:已付 wc:完成)</param>
        /// <returns></returns>        
        public static List<Order> GetAllOrder(string OpenID, string State)
        {
            return OrderBase.GetAllOrder(OpenID, State);
        }
        /// <summary>
        /// 返回Order表的所有数据  
        /// </summary>
        /// <param name="State">状态</param>
        /// <param name="OpenID">微信ID</param>
        /// <returns></returns>        
        public static List<Order> GetEmpOrder(string State, string OpenID)
        {
            return OrderBase.GetEmpOrder(State, OpenID);
        }
        /// <summary>
        /// 根据Order表的OrderID字段返回数据  
        /// </summary>
        /// <param name="orderID">OrderID</param>
        /// <returns></returns>        
        public static Order GetOrderByOrderID(long orderID)
        {
            return OrderBase.GetOrderByOrderID(orderID);
        }
        /// <summary>
        /// 根据Order表的TradeNo字段返回数据  
        /// </summary>
        /// <param name="TradeNo">本方交易单号</param>
        /// <returns></returns>        
        public static Order GetOrderByTradeNo(string TradeNo)
        {
            return OrderBase.GetOrderByTradeNo(TradeNo);
        }
        /// <summary>
        /// 获得订单状态
        /// </summary>
        /// <param name="orderID">OrderID</param>
        /// <returns></returns>       
        public static int GetOrderState(string orderID)
        {
            return OrderBase.GetOrderState(orderID);
        }
        /// <summary>
        /// 判断订单是否已完成支付
        /// </summary>
        /// <param name="TradeNo">交易单号</param>
        /// <returns></returns>       
        public static bool OrderIsPay(string TradeNo)
        {
            return OrderBase.OrderIsPay(TradeNo);
        }
        /// <summary>
        /// 获得排队人数和等待时间
        /// </summary>
        /// <param name="PayDate">支付时间</param>
        /// <returns>[排队人数,等待时间]</returns>       
        public static string[] GetWaitInfo(string PayDate)
        {
            return OrderBase.GetWaitInfo(PayDate);
        }
        /// <summary>
        /// 获得已指派员工
        /// </summary>
        /// <param name="orderID">orderID</param>
        /// <returns></returns>       
        public static string GetUserName(string orderID)
        {
            return OrderBase.GetUserName(orderID);
        }
        /// <summary>
        /// 获得员工派单情况
        /// </summary>
        /// <returns></returns>       
        public static DataTable GetUserAllot()
        {
            return OrderBase.GetUserAllot();
        }
        /// <summary>
        /// 派单
        /// </summary>
        /// <returns></returns>       
        public static bool OrderAllot(string orderID, string userID)
        {
            bool res = false;
            UserDetail um = UserDetailService.Select(userID);
            if (um != null)
            {
                if (UtilityService.UpdateFieldByPK("Order", "State,UserID,UserName,UserMobile", new Object[] { 4, userID, um.TrueName, um.Mobile }, "OrderID", orderID) > 0)
                {
                    NewOrderMessage(long.Parse(orderID), um.WeChat);
                    res = true;
                }
            }
            return res;
        }
        /// <summary>
        /// 新订单通知
        /// </summary>
        /// <param name="orderID">交易ID</param>
        /// <param name="weChat">员工微信号</param>
        /// <returns></returns>       
        public static void NewOrderMessage(long orderID, string weChat)
        {
            Order Model = GetOrderByOrderID(orderID);
            if (Model != null)
            {
                string data = "\"first\":{\"value\":\"您有新的订单\"}," +
                              "\"keyword1\":{\"value\":\"" + Model.OrderNo + "\",\"color\":\"#173177\"}," +
                              "\"keyword2\":{\"value\":\"" + Model.PayDate.ToString() + "\",\"color\":\"#173177\"}," +
                              "\"remark\":{\"value\":\"请及时处理！\"}";

                string templateId = WebConfigHelper.GetAppSet("NewTempID");
                string url = WebConfigHelper.GetAppSet("WebUrl") + "/wechat/emplist.html";
                MessageBll mbll = new MessageBll();
                if (!string.IsNullOrEmpty(weChat))
                {
                    mbll.SendTempMessage(weChat, templateId, data, url);
                }
            }
        }
        /// <summary>
        /// 取消订单通知
        /// </summary>
        /// <param name="orderID">交易ID</param>
        /// <param name="reason">原因</param>
        /// <returns></returns>       
        public static void CancelMessage(long orderID, string reason)
        {
            Order Model = GetOrderByOrderID(orderID);
            if (Model != null)
            {
                string remark = "";
                if (!string.IsNullOrEmpty(Model.PayNo) && Model.Pay.Value > 0)
                {
                    remark = "我们将在7个工作日内为您退款，";
                }
                string data = "\"first\":{\"value\":\"您的订单已取消\"}," +
                              "\"keyword1\":{\"value\":\"" + Model.OrderNo + "\",\"color\":\"#173177\"}," +
                              "\"keyword2\":{\"value\":\"" + Model.CarNumber + (Model.Interior == 1 ? "(外观精洗+内饰简洗)" : "(外观精洗)") + "\",\"color\":\"#173177\"}," +
                              "\"keyword3\":{\"value\":\"" + reason + "\",\"color\":\"#173177\"}," +
                              "\"remark\":{\"value\":\"" + remark + "如有疑问请联系客服。\"}";

                string templateId = WebConfigHelper.GetAppSet("CancelTempID");
                string url = "";
                //string url = WebConfigHelper.GetAppSet("WebUrl") + "/wechat/emplist.html";
                string touser = Model.OpenID;
                MessageBll mbll = new MessageBll();
                if (!string.IsNullOrEmpty(touser))
                {
                    mbll.SendTempMessage(touser, templateId, data, url);
                }
            }
        }
        /// <summary>
        /// 退款成功通知
        /// </summary>
        /// <param name="orderID">交易ID</param>
        /// <param name="weChat">员工微信号</param>
        /// <returns></returns>       
        public static void RefundMessage(string orderNo, string money, string weChat)
        {
            string data = "\"first\":{\"value\":\"您的订单已经完成退款，已经退回您的账户，请留意查看。\"}," +
                          "\"keyword1\":{\"value\":\"" + orderNo + "\",\"color\":\"#173177\"}," +
                          "\"keyword2\":{\"value\":\"¥" + money + "\",\"color\":\"#173177\"}," +
                          "\"remark\":{\"value\":\"！如有疑问请及时联系客服。\"}";

            string templateId = WebConfigHelper.GetAppSet("RefundTempID");
            string url = WebConfigHelper.GetAppSet("WebUrl") + "/wechat/index.html?at=wallet";
            MessageBll mbll = new MessageBll();
            if (!string.IsNullOrEmpty(weChat))
            {
                mbll.SendTempMessage(weChat, templateId, data, url);
            }
        }
        /// <summary>
        /// 洗车完成通知
        /// </summary>
        /// <param name="orderID">交易ID</param>
        /// <returns></returns>       
        public static void FinishOrderMessage(string orderID)
        {
            Order Model = GetOrderByOrderID(long.Parse(orderID));
            if (Model != null)
            {
                string data = "\"first\":{\"value\":\"您的爱车已经洗好\"}," +
                              "\"keyword1\":{\"value\":\"" + Model.OrderNo + "\",\"color\":\"#173177\"}," +
                              "\"keyword2\":{\"value\":\"" + Model.CarNumber + (Model.Interior == 1 ? "(外观精洗+内饰简洗)" : "(外观精洗)") + "\",\"color\":\"#173177\"}," +
                              "\"keyword3\":{\"value\":\"" + Model.StartTime.ToString() + "\",\"color\":\"#173177\"}," +
                              "\"keyword4\":{\"value\":\"" + Model.EndTime.ToString() + "\",\"color\":\"#173177\"}," +
                              "\"remark\":{\"value\":\"祝您生活愉快！\"}";

                string templateId = WebConfigHelper.GetAppSet("FinishTempID");
                //string url = WebConfigHelper.GetAppSet("WebUrl") + "/wechat/list.html";
                string url = "";
                string touser = Model.OpenID;
                MessageBll mbll = new MessageBll();
                mbll.SendTempMessage(touser, templateId, data, url);
            }
        }

        #endregion
        #region delete data
        /// <summary>
        /// 根据Order表的OrderID字段删除数据 
        /// </summary>
        /// <param name="orderID">orderID</param>
        /// <returns>返回受影响的行数</returns>
        public static int DeleteOrderByOrderID(long orderID)
        {
            return OrderBase.DeleteOrderByOrderID(orderID);
        }
        #endregion
        #region update data
        ///<summary>
        ///事务更新数据
        ///</summary>
        ///<param name="al">SQL语句(ArrayList)</param>
        ///<returns>True/False</returns>
        public static bool TransUpdate(ArrayList al)
        {
            return OrderBase.TransUpdate(al);
        }
        /// <summary>
        /// 取消订单
        /// </summary>
        /// <param name="orderID">OrderID</param>
        /// <returns>成功返回null，错误返回错误信息</returns>
        public static string Cancel(string orderID)
        {
            string result = string.Empty;
            Order o = OrderService.GetOrderByOrderID(long.Parse(orderID));
            if (o != null)
            {
                int state = o.State.Value;
                if (state == 0 || state == 1)
                {
                    int newState = 9;
                    if (!string.IsNullOrEmpty(o.PayNo) && o.Pay.Value > 0)
                    {
                        newState = 7;
                    }
                    ArrayList sqlList = new ArrayList();
                    sqlList.Add(UpdateState_SQL(o.OrderID.Value, newState));
                    if (o.CouponsID > 0)
                    {
                        sqlList.Add(CouponsService.UpdateUse_SQL(o.CouponsID.Value, 0));
                    }
                    if (o.Cash > 0)
                    {
                        MemberAccount ma = new MemberAccount();
                        ma.OpenID = o.OpenID;
                        ma.OpType = BLL.EnumHelper.AccountType.退款.ToString();
                        ma.Money = o.Cash;
                        ma.TradeID = o.OrderNo;
                        ma.Date = DateTime.Now;
                        sqlList.Add(MemberAccountService.AddMemberAccount_SQL(ma));
                    }
                    if (TransUpdate(sqlList))
                    {
                        CancelMessage(long.Parse(orderID), "用户主动取消");
                    }
                    else
                    {
                        result = "订单取消失败";
                    }
                }
                else
                {
                    result = "订单" + DictionaryService.GetDicName("订单状态", state.ToString());
                }
            }
            else
            {
                result = "获取订单失败";
            }
            return result;
        }
        /// <summary>
        /// 员工取消订单
        /// </summary>
        /// <param name="orderID">OrderID</param>
        /// <returns>成功返回null，错误返回错误信息</returns>
        public static string EmpCancel(string orderID)
        {
            string result = string.Empty;
            Order o = OrderService.GetOrderByOrderID(long.Parse(orderID));
            if (o != null)
            {
                int state = o.State.Value;
                if (state == 4)
                {
                    int newState = 9;
                    if (!string.IsNullOrEmpty(o.PayNo) && o.Pay.Value > 0)
                    {
                        newState = 7;
                    }

                    ArrayList sqlList = new ArrayList();
                    sqlList.Add(UpdateState_SQL(o.OrderID.Value, newState));
                    if (o.CouponsID > 0)
                    {
                        sqlList.Add(CouponsService.UpdateUse_SQL(o.CouponsID.Value, 0));
                    }
                    if (o.Cash > 0)
                    {
                        MemberAccount ma = new MemberAccount();
                        ma.OpenID = o.OpenID;
                        ma.OpType = BLL.EnumHelper.AccountType.退款.ToString();
                        ma.Money = o.Cash;
                        ma.TradeID = o.OrderNo;
                        ma.Date = DateTime.Now;
                        sqlList.Add(MemberAccountService.AddMemberAccount_SQL(ma));
                    }
                    if (TransUpdate(sqlList))
                    {
                        CancelMessage(long.Parse(orderID), "双方协商一致");
                    }
                    else
                    {
                        result = "订单取消失败";
                    }
                }
                else
                {
                    result = "订单" + DictionaryService.GetDicName("订单状态", state.ToString());
                }
            }
            else
            {
                result = "获取订单失败";
            }
            return result;
        }
        /// <summary>
        /// 开始洗车
        /// </summary>
        /// <param name="orderID">OrderID</param>
        /// <returns>成功返回null，错误返回错误信息</returns>
        public static string Start(string orderID)
        {
            string result = string.Empty;
            object[] orderObj = UtilityService.GetFieldValueByPK("Order", "State", "OrderID", orderID);
            if (orderObj != null && orderObj[0] != null)
            {
                string state = orderObj[0].ToString();
                if (state == "4")
                {
                    if (UtilityService.UpdateFieldByPK("Order", "State,StartTime", new Object[] { 2, DateTime.Now.ToString() }, "OrderID", orderID) <= 0)
                    {
                        result = "操作失败";
                    }
                }
                else
                {
                    result = "订单" + DictionaryService.GetDicName("订单状态", state.ToString());
                }
            }
            else
            {
                result = "获取订单状态失败";
            }

            return result;
        }
        /// <summary>
        /// 完成洗车
        /// </summary>
        /// <param name="orderID">OrderID</param>
        /// <returns>成功返回null，错误返回错误信息</returns>
        public static string Cmplete(string orderID)
        {
            string result = string.Empty;
            Order o = OrderService.GetOrderByOrderID(long.Parse(orderID));
            if (o != null)
            {
                string state = o.State.ToString();
                if (state == "2")
                {
                    int RealTime = 0;
                    DateTime EndTime = DateTime.Now;
                    if (o.StartTime != null)
                    {
                        TimeSpan ts = EndTime - o.StartTime.Value;
                        RealTime = ts.Minutes;
                    }
                    if (UtilityService.UpdateFieldByPK("Order", "State,EndTime,RealTime", new Object[] { 3, EndTime.ToString(), RealTime }, "OrderID", orderID) > 0)
                    {
                        //添加消费记录
                        if ((o.CouponsID == null || o.CouponsID == 0) && !string.IsNullOrEmpty(o.PayNo))
                        {
                            try
                            {
                                if (!MemberPayService.IsExistTradeNo(o.PayNo))
                                {
                                    MemberPay mp = new MemberPay();
                                    mp.OpenID = o.OpenID;
                                    mp.Money = o.Pay;
                                    mp.TradeNo = o.PayNo;
                                    mp.Date = DateTime.Now;
                                    MemberPayService.AddMemberPay(mp);
                                }
                            }
                            catch (Exception ex)
                            {
                                Log.Info("OrderService", "添加消费记录出错:" + ex.Message);
                            }
                        }
                        FinishOrderMessage(orderID);
                    }
                    else
                    {
                        result = "操作失败";
                    }
                }
                else
                {
                    result = "订单" + DictionaryService.GetDicName("订单状态", state.ToString());
                }
            }
            else
            {
                result = "获取订单失败";
            }
            return result;
        }
        /// <summary>
        /// 退款
        /// </summary>
        /// <param name="orderID">OrderID</param>
        /// <returns>成功返回null，错误返回错误信息</returns>
        public static string Refund(string orderID)
        {
            string result = string.Empty;
            Order o = OrderService.GetOrderByOrderID(long.Parse(orderID));
            if (o != null)
            {
                if (o.State.Value == 7)
                {
                    if (UtilityService.UpdateFieldByPK("Order", "State", new Object[] { DictionaryService.GetDicValue("订单状态", "已退款") }, "OrderID", orderID) > 0)
                    {
                        if (MemberAccountService.GetRefund(o.OrderNo) <= 0)
                        {
                            MemberAccount m = new MemberAccount();
                            m.OpenID = o.OpenID;
                            m.OpType = EnumHelper.AccountType.退款.ToString();
                            m.Money = o.Pay;
                            m.Date = DateTime.Now;
                            m.TradeID = o.OrderNo;
                            if (MemberAccountService.AddMemberAccount(m) > 0)
                            {
                                RefundMessage(o.OrderNo, o.Pay.ToString(), o.OpenID);
                            }
                        }
                    }
                    else
                    {
                        result = "退款失败";
                    }
                }
                else
                {
                    result = "订单" + DictionaryService.GetDicName("订单状态", o.State.ToString());
                }
            }
            else
            {
                result = "获取订单状态失败";
            }

            return result;
        }
        #endregion
        #region insert data
        /// <summary>
        /// 向Order表插入一条数据，插入成功则返回自增列数值，插入不成功则返回-1 
        /// </summary>
        /// <param name="order">Order</param>        
        /// <returns></returns>
        public static int AddOrder(Order order)
        {
            return OrderBase.AddOrder(order);
        }
        #endregion
        #endregion

        #region .SQL语句汇总.
        /// <summary>
        /// 向Order表插入一条数据（SQL语句）
        /// </summary>
        /// <param name="o">Order</param>       
        /// <returns></returns>        
        public static string AddOrder_SQL(Order o)
        {
            return OrderBase.AddOrder_SQL(o);
        }
        /// <summary>
        /// 更新状态（SQL语句）
        /// </summary> 
        /// <param name="orderID">OrderID</param>
        /// <param name="isUse">是否使用</param>
        /// <returns></returns>       
        public static string UpdateState_SQL(long orderID, int state)
        {
            return OrderBase.UpdateState_SQL(orderID, state);
        }
        /// <summary>
        /// 返回Order表的所有数据 （SQL语句）
        /// </summary>
        /// <param name="State">状态</param>
        /// <param name="Mobile">手机号</param>
        /// <param name="OrderNo">订单号</param>
        /// <returns></returns>        
        public static string GetAllOrder_SQL(string State, string Mobile, string OrderNo)
        {
            return OrderBase.GetAllOrder_SQL(State, Mobile, OrderNo);
        }
        #endregion
    }
}